package cn.hpclub.server.controller.admin;

import java.io.File;

import com.baidu.ueditor.define.ActionMap;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;

import cn.hpclub.server.model.Admin;
import cn.hpclub.server.util.UedtiorConfigUtil;
import cn.hpclub.server.util.UploadFileUtil;

/**
 * 百度编辑器
 * 
 * @author L.cm
 * @date Nov 27, 2013 9:48:07 PM
 */
@ControllerBind(controllerKey = "/ueditor")
public class UeditorController extends BaseAdminController<Admin>{

    private static final Logger logger = Logger.getLogger(UeditorController.class);

    // 上传图片
    public void upload(){
        logger.debug("=== uploadImg ===");
        String actionType = getPara("action");
        if(StrKit.notBlank(actionType)){
            if(!ActionMap.mapping.containsKey(actionType)){
                renderJson(new BaseState(false, AppInfo.INVALID_ACTION).toJSONString());
                return;
            }
            int actionCode = ActionMap.getType(actionType);
            switch(actionCode){
                case ActionMap.CONFIG:
                    String str = UedtiorConfigUtil.getUeditorConfig();
                    // System.out.println(str);
                    renderJson(str);
                    return;
                case ActionMap.UPLOAD_IMAGE:
                    savefile();
                    return;
                default:
                    return;
            }
        }

        // 选择保存目录
        String fetch = getPara("fetch");
        if(StrKit.notBlank(fetch)){
            String str = "updateSavePath( [\"" + "/upload" + "\"] );";
            // System.out.println(str);
            renderJavascript(str);
            return;
        }
        savefile();
        return;
    }

    private void savefile(){
        File upload = null;
        String uploadFileName = null;
        UploadFile upfile = getFile();
        if(upfile != null){
            upload = upfile.getFile();
            uploadFileName = upfile.getFileName();
        }
        if(upload == null){
            setAttr("state", "请选择上传文件！");
            renderJson(new String[] { "state" });
            return;
        }
        String uploadFilePath = UploadFileUtil.saveImage(upload);
        setAttr("original", uploadFileName);
        setAttr("url", uploadFilePath);
        setAttr("state", "SUCCESS");
        // "SUCCESS", "SUCCESS"
        setAttr("title", getPara("pictitle"));
        render(new JsonRender(new String[] { "original", "url", "title", "state" }).forIE());
        //renderJson(new String[] { "original", "url", "title", "state" });
        // "{'original':'"+up.getOriginalName()+"','url':'"+up.getUrl()+"','title':'"+up.getTitle()+"','state':'"+up.getState()+"'}"
    }
}
